package cn.yaoud.salus.imexport.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

import cn.yaoud.salus.async.task.constant.TaskConstant;
import cn.yaoud.salus.async.task.util.CommonUtil;
import cn.yaoud.salus.common.file.core.FileProperties;
import cn.yaoud.salus.common.file.core.FileTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wny
 * @date 2025/3/3 14:23
 * @description
 */
@Slf4j
@Component
public class OssUtils {

    public static String uploadFile(File file) {
        try {
            FileProperties fileProperties = SpringContext.getBean(FileProperties.class);
            FileTemplate fileTemplate = SpringContext.getBean(FileTemplate.class);
            String fileId = CommonUtil.buildFileId(file.getName());
            try (InputStream inputStream = new FileInputStream(file)) {
                fileTemplate.putObject(fileProperties.getBucketName(), fileId, inputStream);
            } catch (Exception e) {
                log.error("上传失败", e);
            }
            return fileId;
        } catch (Exception e) {
            log.error("上传文件至oss失败", e);
            return null;
        }
    }

    public static void updateProcess(Long taskId, Long successNum, Long totalNum) {
        RedisTemplate redisTemplate = SpringContext.getBean(RedisTemplate.class);
        redisTemplate.opsForValue().set("TASK:ASYNC_TASK_REDIS_TOTAL_NUM_" + taskId, totalNum,
            TaskConstant.REDIS_EXPIRATION_TIME, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("TASK:ASYNC_TASK_REDIS_SUCCESS_NUM_" + taskId, successNum,
            TaskConstant.REDIS_EXPIRATION_TIME, TimeUnit.SECONDS);
        log.info("更新任务执行数量成功数量taskId:" + taskId + ",successNum:" + successNum + ",totalNum:" + totalNum);

    }

    public static S3ObjectInputStream readOssFile(String ossFileUrl) {
        try {
            FileProperties fileProperties = SpringContext.getBean(FileProperties.class);
            FileTemplate fileTemplate = SpringContext.getBean(FileTemplate.class);
            String host = fileProperties.getOss().getHost() + "/";
            S3Object s3Object = fileTemplate.getObject(fileProperties.getBucketName(), ossFileUrl.replace(host, ""));
            return s3Object.getObjectContent();
        } catch (Exception e) {
            log.error("根据文件转成流", e);
            return null;
        }
    }
}
